package domain;

import java.io.Serializable;

import org.springframework.dao.DataAccessException;

import util.DAOException;
import util.VersionException;
import domain.factory.POJOFactory;
import domain.itf.IDAOPhoneNumber;

public class DAOPhoneNumber extends AbstractDAO implements IDAOPhoneNumber {

	public DAOPhoneNumber() {
		super();
	}

	
	public PhoneNumber getByIdDB(int id) throws DAOException {
		try {
			Object phoneO = super.getHibernateTemplate().get(PhoneNumber.class, id);
			if (phoneO != null && phoneO instanceof PhoneNumber)
				return (PhoneNumber) phoneO;
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		throw new DAOException("Impossible to get the phone number. getById(" + id + ").");
	}

	
	public PhoneNumber addPhoneNumber(String phoneKind, String phoneNumber,
			Contact contact) throws DAOException {
		return this.addPhoneNumberDB(POJOFactory.instance.newPhoneNumber(phoneKind, phoneNumber, contact));
	}

	
	public PhoneNumber addPhoneNumberDB(PhoneNumber phone) throws DAOException {
		try {
			Serializable newId = super.getHibernateTemplate().save(phone);
			if (newId instanceof Integer)
				phone.setId((Integer) newId);
			else // all ids are Integer in our database
				throw new DAOException("Impossible to get the id of the new phone number.");
			return phone;
		} catch (DataAccessException e) {
			e.printStackTrace();
			throw new DAOException("Impossible to create the phone number. " + e.getMessage());
		}
	}

	
	public PhoneNumber updatePhoneNumber(int id, long version, String phoneKind,
			String phoneNumber, Contact contact) throws DAOException, VersionException {
		PhoneNumber pn = POJOFactory.instance.newPhoneNumber(phoneKind, phoneNumber, contact);
		pn.setId(id);
		pn.setVersion(version);
		return this.updatePhoneNumberDB(pn);
	}

	
	public PhoneNumber updatePhoneNumberDB(PhoneNumber phoneNumber) throws DAOException, VersionException {
		// versionning verification
		long version = super.getVersionDB(PhoneNumber.class, phoneNumber.getId());
		if (version != phoneNumber.getVersion())
			throw new VersionException();

		try {
			// update the version before save the adress modification
			phoneNumber.setVersion(phoneNumber.getVersion() + 1);
			super.getHibernateTemplate().update(phoneNumber);
			return phoneNumber;
		} catch(DataAccessException e) {
			e.printStackTrace();
			throw new DAOException("Impossible to update the phoneNumber. " + e.getMessage());
		}
	}

	
	public boolean deletePhoneNumberDB(int id) throws DAOException {
		PhoneNumber newPhoneNumber = this.getByIdDB(id);
		try{
			super.getHibernateTemplate().delete(newPhoneNumber);
			return true;
		} catch(DataAccessException e) {
			e.printStackTrace();
			throw new DAOException("Impossible to delete the phone number. " + e.getMessage());
		}
	}
}
